package com.supermap.qdsearch.activity;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.TextView;

import com.supermap.qdsearch.R;
import com.supermap.qdsearch.utils.ConstUtils;
import com.supermap.qdsearch.utils.SPUtils;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionNo;
import com.yanzhenjie.permission.PermissionYes;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class FlashActivity extends AppCompatActivity {

    @BindView(R.id.iv_flash)
    ImageView ivFlash;
    @BindView(R.id.tv_info)
    TextView tvInfo;
    Map<String,String> map = new HashMap<>();
    private RationaleListener rationaleListener = new RationaleListener() {
        @Override
        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
            AlertDialog.newBuilder(FlashActivity.this)
                    .setTitle("友好提醒")
                    .setMessage("您已拒绝过相应权限，沒有这些权限无法使用本软件，请授权！")
                    .setPositiveButton("同意", (dialog, which) -> {
                        rationale.resume();
                    })
                    .setNegativeButton("拒绝", (dialog, which) -> {
                        rationale.cancel();
                        finish();
                    }).show();
        }
    };
    private ScheduledExecutorService service;

    SPUtils spUtils = new SPUtils(ConstUtils.SP_KEY);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_flash);
        ButterKnife.bind(this);
        map.put("android.permission.READ_EXTERNAL_STORAGE","存储权限");
        map.put("android.permission.ACCESS_FINE_LOCATION","定位权限");
        map.put("android.permission.CAMERA","相机权限");
        AndPermission.
                with(this).
                rationale(rationaleListener).
                requestCode(300).
                callback(this).
                permission(
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.CAMERA).
                start();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    boolean isStart;

    @PermissionYes(300)
    private void getPermissionYes(List<String> grantedPermissions) {
        //申请权限成功。
        if (!isStart) {
            //启动右上角时间提示定时器
            startSecondInfo();

            //启动动画
            startAnimation();

            isStart = true;
        }

    }

    @PermissionNo(300)
    private void getPermissionNo(List<String> deniedPermissions) {
        String msg = "（";
        for (int i = 0; i < deniedPermissions.size(); i++) {
            String permission = deniedPermissions.get(i);
            String s = map.get(permission);
            if(i==deniedPermissions.size()-1){
                msg+=s+"）";
            }else{
                msg+=s+"、";
            }
        }
        // 是否有不再提示并拒绝的权限。
        if (AndPermission.hasAlwaysDeniedPermission(this, deniedPermissions)) {
            // 第二种：用自定义的提示语。
            AndPermission.defaultSettingDialog(this, 400)
                    .setTitle("权限申请失败")
                    .setMessage("您拒绝了我们必要的权限"+msg+"，将不能使用本软件，请在设置中授权！")
                    .setPositiveButton("去设置")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();
                        }
                    })
                    .show();
        }else{
            AndPermission.
                    with(this).
                    rationale(rationaleListener).
                    requestCode(300).
                    callback(this).
                    permission(
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.CAMERA).
                    start();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (service != null)
            service.shutdown();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 400||requestCode == 100) {
            if (AndPermission.hasPermission(this,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.CAMERA)) {

                //启动右上角时间提示定时器
                startSecondInfo();

                //启动动画
                startAnimation();
            } else {
                AndPermission.defaultSettingDialog(this, 100);
            }
        }
    }

    int index = 3;

    //启动右上角时间提示定时器
    public void startSecondInfo() {
        service = new ScheduledThreadPoolExecutor(3);
        service.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvInfo.setText(index + "s");
                    }
                });

                index--;
                if (index == 0) {
                    service.shutdown();
                }
                Log.e("index", index + "");

            }
        }, 0, 1, TimeUnit.SECONDS);  //延迟0秒  每一秒执行一次


    }

    //启动动画
    public void startAnimation() {
        AlphaAnimation alphaAnimation = new AlphaAnimation(1f, 0.5f);
        alphaAnimation.setDuration(3000);
        alphaAnimation.setFillAfter(true);
        alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            //动画结束 执行跳转
            @Override
            public void onAnimationEnd(Animation animation) {
                jumpGuidePage();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        ivFlash.startAnimation(alphaAnimation);
    }


    //右上角时间点击事件
    @OnClick(R.id.tv_info)
    public void onViewClicked() {
        jumpGuidePage();
    }


    //跳转Guide Activity
    public void jumpGuidePage() {
        String isFirstLogin = spUtils.getString("isFirstLogin", "");

        if ("".equals(isFirstLogin)) {
            Intent intent = new Intent(this, GuideIndicatorActivity.class);
            startActivity(intent);
            spUtils.putString("isFirstLogin","1");
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
//            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }

        finish();

    }

    /**
     * 沉浸式
     * @param hasFocus
     */
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && Build.VERSION.SDK_INT >= 19) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_FULLSCREEN
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
    }
}
